//
//  WoDeViewController.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/24.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "WoDeViewController.h"
#import "LoginViewController.h"
#import "SYRequestAPI+Wode.h"
#import "AppDelegate.h"

#import "CHAlertView.h"
#import "SYBaiBanFuDaoViewController.h"



@interface WoDeViewController ()<TeacherLeftDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,CHAlertViewDelegate>
@property (nonatomic, strong) UIImageView *headerImageView;//头像
@property (nonatomic, strong) UILabel *nameLabel;//姓名
@property (nonatomic, strong) UILabel *detailLabel;//邮箱
@property (nonatomic, strong) UIButton *quiteAcount;
@property (nonatomic, strong) UIButton *clearBtn;//清空缓存
@end

@implementation WoDeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MAINBACKCOLOR;
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(0, 20, APP_WIDTH, 1);
    lineView.backgroundColor = LINCOLOR;
    [self.view addSubview:lineView];
}
//290-75
- (TeacherLeftView *)leftMenuView{
    if (!_leftMenuView) {
        TeacherLeftView *view = [[TeacherLeftView alloc]initWithFrame:CGRectMake(0, 130, 215*fw, APP_HEIGHT-130) andButtonView:@[@" 账号信息",@" 修改密码",@" 关于",@"清空缓存"] andImageArray:@[@"my_Resource",@"wode_xiugaimima.png",@"wode_guanyu.png",@"wode_delegate.png"]];
        view.delegate = self;
        view.openButton.hidden = YES;
        _leftMenuView = view;
    }
    return _leftMenuView;
}
- (UIView *)baseView{
    if (!_baseView) {
        UIView *view = [[UIView alloc]init];
        view.backgroundColor = [UIColor clearColor];
        _baseView = view;
    }
    return _baseView;
}
- (UIView *)baseLeftView{
    if (!_baseLeftView) {
        UIView *view = [[UIView alloc]init];
        view.frame = CGRectMake(0, 20, 215*fw, APP_HEIGHT-20);
        view.backgroundColor = [UIColor clearColor];
        _baseLeftView = view;
    }
    return _baseLeftView;
}
#pragma mark - 添加子视图
- (void)initSubView{
    self.view.backgroundColor = CONTENTBACKCOLOR;
    _allViewArray = [NSMutableArray new];
    for (int i = 0; i<3; i++) {
        
        if (i == 0) {
            _woDeAcountVC = [[WoDeAcountVC alloc]init];
            _woDeAcountVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
            _woDeAcountVC.view.backgroundColor = [UIColor whiteColor];
            [_allViewArray addObject:_woDeAcountVC];
        }else if (i==6){//暂时c去掉 我的财富
            _woDeCaiFuVC = [[MyTreasureVC alloc]init];
            _woDeCaiFuVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
            _woDeCaiFuVC.view.backgroundColor = [UIColor whiteColor];
            [_allViewArray addObject:_woDeCaiFuVC];
        }else if (i == 1){
            _changePassVC = [[MyChangePasswordVC alloc]init];
            _changePassVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
            _changePassVC.view.backgroundColor = [UIColor whiteColor];
            [_allViewArray addObject:_changePassVC];
        }else{
            _guanYuWoMenVC = [[AbountVC alloc]init];
            _guanYuWoMenVC.view.frame = CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT);
            _guanYuWoMenVC.view.backgroundColor = [UIColor whiteColor];
            [_allViewArray addObject:_guanYuWoMenVC];
        }
    }
    [self.view addSubview:self.baseLeftView];
    [_baseLeftView addSubview:self.headerImageView];
    [_headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@42);
        make.top.equalTo(@46);
        make.width.equalTo(@64);
        make.height.equalTo(@64);
    }];
    
    [_baseLeftView addSubview:self.nameLabel];
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_headerImageView.mas_right).offset(10);
        make.top.equalTo(self->_headerImageView.mas_top).offset(10);
        make.right.equalTo(self->_baseLeftView.mas_right);
        make.height.equalTo(@20);
    }];
    
    [_baseLeftView addSubview:self.detailLabel];
    [_detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_nameLabel.mas_left);
        make.top.equalTo(self->_nameLabel.mas_bottom).offset(10);
        make.right.equalTo(self->_baseLeftView.mas_right);
        make.height.equalTo(@20);
    }];
    
//    [_baseLeftView addSubview:self.clearBtn];
//    [self.clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.equalTo(self.baseLeftView);
//        make.top.equalTo(self->_headerImageView.mas_bottom).offset(0);
//        make.height.mas_equalTo(45);
//    }];
    
    [_baseLeftView addSubview:self.leftMenuView];
    [_leftMenuView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.top.equalTo(self->_headerImageView.mas_bottom).offset(0);
        make.width.equalTo(@0).offset(215*fw);
        make.height.equalTo(@0).offset(APP_HEIGHT-130-100);
    }];
    [_baseLeftView addSubview:self.quiteAcount];
    [_quiteAcount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self->_baseLeftView.mas_centerX);
        make.top.equalTo(self->_baseLeftView.mas_top).offset(624*fh);
        make.width.equalTo(@130);
        make.height.equalTo(@40);
    }];
    [self.view addSubview:self.baseView];
    [_baseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.leftMenuView.mas_right);
        make.top.equalTo(@20);
        make.right.equalTo(@0);
        make.bottom.equalTo(@0);
    }];
    [self mineClick:0];
    //切换头像
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeImage:)];
    [self.headerImageView addGestureRecognizer:tap];
    self.nameLabel.text = [SYLoginUserModel sharedSYLoginUserModel].userinfo.name;
    self.detailLabel.text = [SYLoginUserModel sharedSYLoginUserModel].userinfo.serial;
}
- (void)changeImage:(UITapGestureRecognizer *)tap{
    //修改头像暂时没有这个接口
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定修改头像" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *confirm =[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self selectedImageFromeSystemPhotograph];
//    }];
//    UIAlertAction *concel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//
//    }];
//    [alert addAction:confirm];
//    [alert addAction:concel];
//    [self presentViewController:alert animated:YES completion:nil];
    
//    [SYRequestAPI bb_TutorServiceImInfoToken:Token success:^(id  _Nonnull dataList) {
//
//
//        SYBaiBanFuDaoViewController *interactionVC = [[SYBaiBanFuDaoViewController alloc] init];
//        interactionVC.roomId = @"610311";
//        interactionVC.tecentRoom = @"SANYI_10526";
//        interactionVC.userName = [dataList nilObjectForKey:@"imId"];
//        interactionVC.userSig = [dataList nilObjectForKey:@"userSig"];
//        interactionVC.imId = [dataList nilObjectForKey:@"imId"];
//        interactionVC.fdbId = @"10311";
//        interactionVC.accountId =@"10526";
//        interactionVC.tutorRecordName = @"互动课堂2.0测试-第2次辅导";
//        interactionVC.tutorRecordId = @"10311";
//        interactionVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
//        [self presentViewController:interactionVC animated:YES completion:nil];
//
//    } fail:^(NSError *error) {
//
//    }];
    
    
    
}
- (void)initOption{
    
}
- (void)layout{
    
}
#pragma mark - 左侧头像详细
- (UIImageView *)headerImageView{
    if (!_headerImageView) {
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.backgroundColor = [UIColor lightGrayColor];
        imageView.layer.cornerRadius = 32;
        imageView.layer.masksToBounds = YES;
        imageView.userInteractionEnabled  = YES;
        _headerImageView = imageView;
    }
    return _headerImageView;
}
- (UILabel *)nameLabel{
    if (!_nameLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.font = [UIFont systemFontOfSize:14];
        label.textAlignment = 0;
        label.textColor = [UIColor darkGrayColor];
        label.text = @"name";
        _nameLabel = label;
    }
    return _nameLabel;
}
- (UILabel *)detailLabel{
    if (!_detailLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.font = [UIFont systemFontOfSize:13];
        label.textAlignment = 0;
        label.textColor = TITLECOLOR;
        label.text = @"邮箱";
        _detailLabel = label;
    }
    return _detailLabel;
}
- (UIButton *)clearBtn {
    if (!_clearBtn) {
        _clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_clearBtn setTitle:@"清空缓存" forState:UIControlStateNormal];
        [_clearBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
        [_clearBtn addTarget:self action:@selector(clearBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _clearBtn;
}
- (void)clearBtnClick {
    
}
#pragma mark - 左侧按钮点击
- (void)mineClick:(int)index{
    if (index == 3) {
        [self clearCache];
    } else {
        UIViewController *vc = _allViewArray[index];
        if (self.currentVC == _allViewArray[index]) {
            return;
        }else{
            [self addChildViewController:vc];
            vc.view.hidden = NO;
            [self.baseView addSubview:vc.view];
            [vc.view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(self.baseView.mas_left);
                make.right.equalTo(self.baseView.mas_right);
                make.top.equalTo(@0);
                make.bottom.equalTo(self.baseView.mas_bottom);
            }];
            //替换view
            [vc didMoveToParentViewController:self];
            [self.currentVC willMoveToParentViewController:nil];
            [self.currentVC removeFromParentViewController];
            [self.currentVC.view removeFromSuperview];
            self.currentVC.view.hidden = YES;
        }
    }
}
//清空缓存
- (void)clearCache {
    // 获取缓冲文件的沙盒路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSLog(@"有数据的情况下开始清理数据");
    dispatch_async(dispatch_get_main_queue(), ^{
        // 清除缓冲,进行缓冲操作
       //拿到path路径的下一级目录的子文件夹
       NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cachePath error:nil];
       NSString *filePath = nil;
       NSError *error = nil;
       for (NSString *subPath in subPathArr) {
           filePath = [cachePath stringByAppendingPathComponent:subPath];
           //删除子文件夹
           [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
       }
        NSLog(@"清理数据完成");
        [MBProgressHUD mj_showSuccess:@"清理缓存完成"];
    });
}

- (UIButton *)quiteAcount{
    if (!_quiteAcount) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"退出账号" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitleColor:SELECTEDCOLOR forState:UIControlStateNormal];
        button.layer.cornerRadius = 5;
        button.layer.masksToBounds = YES;
        button.layer.borderWidth = 1;
        button.layer.borderColor = SELECTEDCOLOR.CGColor;
        [button addTarget:self action:@selector(quiteAcount:) forControlEvents:UIControlEventTouchUpInside];
        _quiteAcount = button;
    }
    return _quiteAcount;
}
- (void)quiteAcount:(UIButton *)sender{
    //退出接口
//    [MBProgressHUD mj_showMessage:nil toView:self.view];
//    [SYRequestAPI sy_getSafeServiceLogout:@{} success:^(id  _Nonnull responseObject) {
//        NSLog(@"安全退出 %@",responseObject);
//        [MBProgressHUD mj_hideHUDForView:self.view];
//    } fail:^(NSError *error) {
//        [MBProgressHUD mj_hideHUDForView:self.view];
//    }];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定退出" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [USERDEFAL removeObjectForKey:PassDefalut];
        [USERDEFAL removeObjectForKey:TokenDefalut];
        [USERDEFAL removeObjectForKey:RYUserPathDefalut];
        [USERDEFAL removeObjectForKey:RYUserNameDefalut];
        [USERDEFAL removeObjectForKey:RYUserIdDefalut];
        [USERDEFAL removeObjectForKey:RYTokenDefalut];
        [USERDEFAL removeObjectForKey:RYIMidIDDefalut];
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate.friendsArray removeAllObjects];
        [appDelegate.groupsArray removeAllObjects];
        [appDelegate.AllArray removeAllObjects];
        [[RCIMClient sharedRCIMClient] disconnect];
        
        [self.navigationController removeFromParentViewController];
        LoginViewController *login = [[LoginViewController alloc]init];
        [UIApplication sharedApplication].keyWindow.rootViewController = [[UINavigationController alloc]initWithRootViewController:login];
        [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];

    }];
    [alert addAction:cancel];
    [alert addAction:confirm];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 修改头像
- (void)changeImageHeaderRequest{
    NSDictionary *parama = @{@"head256":@"",
                             @"name":@"",
                             @"sex":@""};
    [SYRequestAPI sy_getAccountServiceModifyAccountInfo:parama success:^(id  _Nonnull responseObject) {
        NSLog(@"修改成功 %@",parama);
    } fail:^(NSError *error) {
        
    }];
}

#pragma mark - 相片选择
- (void)selectedImageFromeSystemPhotograph{
    UIAlertController * _alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        UIImagePickerController * picker  = [[UIImagePickerController alloc]init];
        picker.definesPresentationContext = YES;
        picker.modalPresentationStyle = UIModalPresentationOverCurrentContext;//横屏
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction * Camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        UIImagePickerController * picker = [UIImagePickerController new];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.definesPresentationContext = YES;
        picker.modalPresentationStyle = UIModalPresentationOverCurrentContext;//防止竖屏
        picker.sourceType = sourceType;
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:YES completion:nil];
    }];
    [_alertVC addAction:cancel];
    [_alertVC addAction:photo];
    [_alertVC addAction:Camera];
    [self presentViewController:_alertVC animated:YES completion:nil];
}
-(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark--从相册中选择图片
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //上传图片先不写
//    [picker dismissViewControllerAnimated:YES completion:nil];
//
//    UIImage * image = [info objectForKey: UIImagePickerControllerEditedImage];
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    dispatch_group_t group2 = dispatch_group_create();
//    dispatch_group_async(group2,dispatch_get_global_queue(0, 0), ^{
//
//    });
//    dispatch_group_notify(group2, dispatch_get_main_queue(), ^{
//        //网络请求完毕 回到主线程更新UI 或者做些其它的操作
//        self->_headerImageView.image = image;
//        [self selectPic:image];
//        [MBProgressHUD hideHUDForView: self.view animated:YES];
//    });
}
- (void)selectPic:(UIImage*)image
{
    NSDictionary *parama = @{@"head256":@"http://wx.qlogo.cn/mmopen/icibkqIgzXgfHHf6wRBloLzOFXel5kfaRjnljGF91NNQ7vo8Wvy2JxgsanG7jkmRicBujoVC0xT5DedPkE8ibKQVUxWXhBgbl1wA/0",
                             @"name":@"",
                             @"sex":@""};
    [SYRequestAPI sy_getAccountServiceModifyAccountInfo:parama success:^(id  _Nonnull responseObject) {
        NSLog(@"修改成功 %@",parama);
    } fail:^(NSError *error) {
        NSLog(@"修改头像失败 %@",error);
    }];
//   NSData *imageData = UIImageJPEGRepresentation(image,0.6f);
//    NSDictionary *parama = @{@"head256":@"",
//                             @"name":@"",
//                             @"sex":@""};
//    [SYRequestAPI uploadFileRequest:image andURL:@"http://apipad.mykeyu.cn/resource/MyResourceService.svc/UploadFile" andParama:parama andAcountID:@"id" success:^(id responseObject) {
//        NSLog(@"修改成功 %@",responseObject);
//    } fail:^(NSError *error) {
//       NSLog(@"修改失败 %@",error);
//    }];
}

@end
